package auth

import (
	v1 "gitee.com/sweetsunnyflower/carpooling-server-go/app/http/controllers/api/v1"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/user"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/requests"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/services"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/jwt"
	"github.com/gofiber/fiber/v2"
)

type LoginController struct {
	v1.BaseController
}

func (controller *LoginController) MiniprogramLogin(c *fiber.Ctx) error {

	request := new(requests.MiniprogramLoginRequest)

	if errors := requests.ValidateMiniprogramLogin(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	miniProgram := services.NewMiniProgram()

	openId, err := miniProgram.Login(request.Code)

	if err != nil {
		return controller.Faield(c, err.Error())
	}

	user := user.CreateUserIfNotExistByOpenid(openId)

	if user.ID <= 0 {
		return controller.Faield(c, "登录失败")

	}

	token, err := jwt.New().CreateToken(user.GetStringID(), user.OpenId, "api")

	if err != nil {
		return controller.Faield(c, err.Error())
	}

	return controller.Json(c, map[string]interface{}{
		"token": token,
		"user":  user,
	})
}

func (controller *LoginController) RefreshToken(c *fiber.Ctx) error {
	// token, err := jwt.New().RefreshToken(c)

	// if err != nil {
	// 	return controller.Faield(c, err.Error())
	// } else {
	// 	return controller.Json(c, map[string]interface{}{
	// 		"token": token,
	// 	})
	// }
	return controller.Success(c)
}
